import "./header.js"
import {querystring,distinctAry} from "./tools.js"
import {generateSeats,ticketIndexAry} from "./seats.js"


let {filmId,cinemaId,scheduleIndex,screenIndex} = querystring.parse(location.search);

$.ajax({
    type:"get",
    url:`/api/filmAndCinemas/films/${filmId}/cinemas/${cinemaId}`,
    success:function(data){
        if(data.length > 0){
            show(data[0]);
        }
        
    }
});

//显示座位及电影信息
const show = function(data){
    // 选择的院线
    let cinemas = data.cinemas;
    // 选择的放映厅
    let screen = data.schedule[scheduleIndex].screens[screenIndex];
    //根据已拍片的放映厅的名字找到院线中对应的放映厅，获取它的座位信息
    let seatAry;
    
    for(let i = 0;i < cinemas.screens.length;i++){   
        if(cinemas.screens[i].name == screen.name){   
            seatAry = JSON.parse(cinemas.screens[i].seat);
        }
    }
    // console.log("seatsAry",seatAry);
    if(!seatAry || seatAry.length <= 0){
        alert("没有该放映厅的座位信息");
    }else{
        //生成座位
        generateSeats(seatAry,screen.tickets||[]);
    }
    
    // 显示电影及院线信息到页面上
    $(".name-info").append(data.films.name);
    $(".screening-info").append(data.cinemas.name);
    $(".version-info").append(screen.type);

    // 当点击购买按钮时，将购票信息录入数据库
    $("input:button").click(function(){
        //循环电影院线匹配集合中的放映厅，找到当前选择的放映厅，然后将购票的数据添加进去
        for(let i = 0;i < data.schedule[scheduleIndex].screens.length;i++){
            
            if(!screen.tickets){
                screen.tickets = [];
            }
            // 将新购买的电影票和之前已购买的电影票合并，然后去重
            let newAry = screen.tickets.concat(ticketIndexAry);
            screen.tickets = distinctAry(newAry);
           
        }
        $.ajax({
            type:"put",
            url:"/api/filmAndCinemas/"+data._id,
            data:{
                schedule:JSON.stringify(data.schedule)
    
            },
            success:function(){
                alert("suc");
                window.location = `/screens.html?filmId=${filmId}&cinemaId=${cinemaId}`
            }
    
        });
    });
}


